package miroshnichenko.gallery.web.gallery;

import miroshnichenko.gallery.dao.ImageItemDao;
import miroshnichenko.gallery.domain.ImageItem;
import miroshnichenko.gallery.service.ThumbnailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/gallery")
public class GalleryController {

    private Logger log = LoggerFactory.getLogger(GalleryController.class);

    @Autowired
    private ImageItemDao imageItemDao;

    @Autowired
    private ThumbnailService thumbnailService;

    @RequestMapping(value = "/my", method = RequestMethod.GET)
    public String viewMyGallery() {
        return "myGallery";
    }

//    @RequestMapping(value = "/img/{imageId}",
//            produces = { "image/jpeg", "image/jpg", "image/png" },
//            method = RequestMethod.GET)
//    public @ResponseBody byte[] viewImage(@PathVariable("imageId") int imageId, WebRequest request) {
//        long lastModified = 1;
//        if (request.checkNotModified(lastModified)) return null;
//        return imageItemDao.retrieveImage(imageId).getFileContent();
//    }

    //Chrome doesn't cached images after this response
    @RequestMapping(value = "/img/{imageId}",
            produces = { "image/jpeg", "image/jpg", "image/png" },
            method = RequestMethod.GET)
    public @ResponseBody byte[] viewImage(@PathVariable("imageId") Integer imageId) {
        return imageItemDao.retrieveImage(imageId).getFileContent();
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String uploadFile() {
        return "imageupload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file")MultipartFile file) {

        if (file.isEmpty() || !fileContentTypeValidate(file.getContentType())) {
            log.info("Trying upload empty or wrong MIME type file.");
            return "redirect:/gallery/upload?result=fault";
        }

        ImageItem imageItem = new ImageItem();
        imageItem.setFileName(file.getOriginalFilename());
        imageItem.setFileType(file.getContentType());

        String uploadStatus;
        try {
            imageItem.setFileContent(file.getBytes());
            imageItemDao.uploadImage(imageItem);
            uploadStatus = "success";
        } catch (IOException ioe) {
            log.error("IO exception while uploading file", ioe);
            uploadStatus = "fault";
        }

        return "redirect:/gallery/upload?result=" + uploadStatus;
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public @ResponseBody List<Integer> loadThumbnails(@RequestParam Integer fromItem) {
        return imageItemDao.retrieveThumbnailsIdList(fromItem, 12);
    }

    @RequestMapping(value = "/img/thumb/{imageId}",
            produces = { "image/jpeg", "image/jpg", "image/png" },
            method = RequestMethod.GET)
    public @ResponseBody BufferedImage viewThumbnail(@PathVariable ("imageId") int imageId) throws IOException {
        return thumbnailService.getThumbnail(imageId);
    }

    private boolean fileContentTypeValidate(String fileContentType) {
        return fileContentType.equals(MediaType.IMAGE_JPEG_VALUE) || fileContentType.equals(MediaType.IMAGE_PNG_VALUE);
    }
}
